package com.ruoyi.qywx.getway.api;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.getway.dto.ChatJoinWay;
import com.ruoyi.qywx.getway.entity.QyExternalChat;
import com.ruoyi.qywx.getway.request.TxRequest;
import com.ruoyi.qywx.getway.request.TxResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : hcl
 * @Date : 2023/9/4 10:45
 * https://developer.work.weixin.qq.com/document/path/92229
 * https://developer.work.weixin.qq.com/document/path/92120
 * 群聊
 */
@Slf4j
public class GroupChatApi {
    /**
     * https://developer.work.weixin.qq.com/document/path/92229#配置客户群进群方式
     */
    public static boolean groupChatAddJoinWay(Meta meta, ChatJoinWay chatJoinWay) {
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/groupchat/add_join_way", JSONUtil.toJsonStr(chatJoinWay));
        if (post.isSuccess()) {
            chatJoinWay.setConfigId(post.getJson().getStr("config_id"));
            return true;
        }
        log.error("创建客户群活码失败: {}", post.getError());
        return false;
    }
    /**
     * https://developer.work.weixin.qq.com/document/path/92229#更新客户群进群方式配置
     */
    public static boolean updateGroupChatAddJoinWay(Meta meta, ChatJoinWay chatJoinWay) {
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/groupchat/update_join_way", JSONUtil.toJsonStr(chatJoinWay));
        if (post.isSuccess()) return true;
        log.error("更新客户群活码失败: {}", post.getError());
        return false;
    }

    /**
     * 获取客户群详情
     * https://developer.work.weixin.qq.com/document/path/92122
     * https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=ACCESS_TOKEN
     */

    public static QyExternalChat getGroupChatDetail(Meta meta, String chatId) {
        if (StrUtils.isEmpty(chatId)) return null;
        Map<String, Object> body = new HashMap<>();
        body.put("chat_id", chatId);
        body.put("need_name", 1);
        TxResponse post = TxRequest.getInstance(meta.getCorpid(), meta.getAppSecret())
                .post("/cgi-bin/externalcontact/groupchat/get", JSONUtil.toJsonStr(body));
        if (post.isSuccess()) {
            return post.getJson().getJSONObject("group_chat").toBean(QyExternalChat.class);
        }
        log.error("获取群详情失败,chatId:{},异常信息:{}", chatId, post.getError());
        return null;
    }


}
